package com.faithbj.common.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Repository;

import com.faithbj.common.model.Region;
import com.faithbj.common.model.User;
import com.faithbj.common.dao.RegionDao;

/**
 * 
 * @author m
 *
 */
@Repository("regionDao")
public class RegionDaoImpl extends BaseDaoImpl<Region, String> implements RegionDao{

	@SuppressWarnings("unchecked")
	@Override
	public List<Region> getRegionListByCurrentUser()
	{
		Object userObject = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<String> regionIds = new ArrayList<String>();
		if (userObject instanceof User)
		{
			User user = (User) userObject;
			Region region = user.getRegion();
			if(!user.getUsername().equals("super"))
			{
				if(region != null)
				{
					getRegionIds(regionIds, region);
				}
				DetachedCriteria detachedCriteria = DetachedCriteria.forClass(getEntityClass());
				Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
				criteria.add(Restrictions.in("parent.id", regionIds));
				return criteria.list();
			}
			else
			{
				return getAll();
			}
		}
		return new ArrayList<Region>();
	}

	private void getRegionIds(List<String> regionIds, Region region)
	{
		regionIds.add(region.getId());
		List<Region> children = findAny("from Region where parent.id=?", region.getId());
		if(children != null)
		{
			for(Region r : children)
			{
				getRegionIds(regionIds, r);
			}
		}
	}
}
